package com.miaoshare.core.base;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;

import com.luck.picture.lib.app.PictureAppMaster;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.entity.MediaExtraInfo;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.utils.MediaUtils;
import com.miaoshare.core.utils.GlideEngine;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportFragment;

/**
 * author: zhengbo
 * date: 2017-11-15.
 */
@SuppressWarnings({"unchecked", "unused"})
public abstract class BaseFragment extends SupportFragment {


    protected LayoutInflater inflater;

    protected Unbinder unbinder = null;
    private final String TAG = getClass().getName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inflater = getActivity().getLayoutInflater();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getContentViewId(), container, false);
        unbinder = ButterKnife.bind(this, view);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        inflater = null;
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    protected abstract @LayoutRes
    int getContentViewId();

    protected void initData() {
    }
//===================================图片选择开始==========================

    /**
     * 选择图片-摄像头
     */
    protected void selectImageCamera() {
        // 单独拍照
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofAll())
                .isOriginalControl(true)
                .isCameraForegroundService(false)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {

                        analyticalSelectResults(result);
                    }

                    @Override
                    public void onCancel() {

                        Log.i(TAG, "PictureSelector Cancel");
                    }
                });

    }

    /**
     * 选择图片-图库
     *
     * @param maxCount 最大选择数量
     */
    protected void selectImageGallery(int maxCount) {
        // 进入相册
        PictureSelector.create(getContext())
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(maxCount)
                .isCameraForegroundService(false)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
//
                        analyticalSelectResults(result);
                    }

                    @Override
                    public void onCancel() {
//
                        Log.i(TAG, "PictureSelector Cancel");
                    }
                });
        // 方式二
//        PictureSelectorFragment selectorFragment = PictureSelector.create(v.getContext())
//                .openGallery(SelectMimeType.ofAll())
//                .setImageEngine(GlideEngine.createGlideEngine())
//                .build();
//        getSupportFragmentManager().beginTransaction()
//                .add(R.id.fragment_container, selectorFragment, selectorFragment.getFragmentTag())
//                .addToBackStack(selectorFragment.getFragmentTag())
//                .commitAllowingStateLoss();;
    }


    /**
     * 选择视频-摄像头
     */
    protected void selectVideoCamera() {
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofVideo())
                .isOriginalControl(true)
                .isCameraForegroundService(false)
                .setRecordVideoMaxSecond(60)
                .setRecordVideoMinSecond(1)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {

                        analyticalSelectResults(result);
                    }

                    @Override
                    public void onCancel() {

                        Log.i(TAG, "PictureSelector Cancel");
                    }
                });
    }

    /**
     * 选择视频-图库
     *
     * @param maxCount 最大选择数量
     */
    protected void selectVideoGallery(int maxCount) {
        PictureSelector.create(getContext())
                .openGallery(SelectMimeType.ofVideo())
                .setMaxSelectNum(maxCount)
                .isCameraForegroundService(false)
                .setMinSelectNum(1)
                .setSelectionMode(maxCount > 1 ? SelectModeConfig.MULTIPLE : SelectModeConfig.SINGLE)
                .setRecordVideoMaxSecond(30)
                .setRecordVideoMinSecond(1)
                .setSelectMaxDurationSecond(30)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
//                        setTranslucentStatusBar();
                        analyticalSelectResults(result);
                    }

                    @Override
                    public void onCancel() {
//                        setTranslucentStatusBar();
                        Log.i(TAG, "PictureSelector Cancel");
                    }
                });
    }


    /**
     * 处理选择结果
     *
     * @param result
     */
    protected ArrayList<LocalMedia> analyticalSelectResults(ArrayList<LocalMedia> result) {
        StringBuilder builder = new StringBuilder();
        builder.append("Result").append("\n");
        for (LocalMedia media : result) {
            if (media.getWidth() == 0 || media.getHeight() == 0) {
                if (PictureMimeType.isHasImage(media.getMimeType())) {
                    MediaExtraInfo imageExtraInfo = MediaUtils.getImageSize(media.getPath());
                    media.setWidth(imageExtraInfo.getWidth());
                    media.setHeight(imageExtraInfo.getHeight());
                } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                    MediaExtraInfo videoExtraInfo = MediaUtils.getVideoSize(PictureAppMaster.getInstance().getAppContext(), media.getPath());
                    media.setWidth(videoExtraInfo.getWidth());
                    media.setHeight(videoExtraInfo.getHeight());
                }
            }
            builder.append(media.getAvailablePath()).append("\n");
            Log.i(TAG, "文件名: " + media.getFileName());
            Log.i(TAG, "是否压缩:" + media.isCompressed());
            Log.i(TAG, "压缩:" + media.getCompressPath());
            Log.i(TAG, "原图:" + media.getPath());
            Log.i(TAG, "绝对路径:" + media.getRealPath());
            Log.i(TAG, "是否裁剪:" + media.isCut());
            Log.i(TAG, "裁剪:" + media.getCutPath());
            Log.i(TAG, "是否开启原图:" + media.isOriginal());
            Log.i(TAG, "原图路径:" + media.getOriginalPath());
            Log.i(TAG, "沙盒路径:" + media.getSandboxPath());
            Log.i(TAG, "原始宽高: " + media.getWidth() + "x" + media.getHeight());
            Log.i(TAG, "裁剪宽高: " + media.getCropImageWidth() + "x" + media.getCropImageHeight());
            Log.i(TAG, "文件大小: " + media.getSize());
        }
        return result;
    }
    //===================================图片选择end==========================
}
